var vapp = new Vue({
	el: "#app",
	data: {
		sysName:"sys_name_1",
		defaultProps : {},
		treelist : [],
		show_bar : true,
		id: "-1",  // 树根节点
		curTreeId: '', // 监控树的节点id
		curTreeLevel:'', // 当前树的层级
		menuInfo: [],
		logo: "../../plugin/images-app/no-img.jpg",
		errlogo: "../../plugin/images-app/error.jpg",
		addable: false,
		editable: true,
		delable: false,
		menuExec: '',
		exec: '',
		info:{
			menu_name:'',
			menu_superior_name:'',
			is_display:'',
			menu_href:'',
			display_order:'',
			menu_rights_name:'',
			target:'',
			iconclass:'',
			menu_logo:'',
			menu_rights:''
		},
		menuForm: false,
		form:{
			menu_name:'',
			menu_superior_name:'',
			is_display:'',
			menu_href:'',
			display_order:'',
			menu_rights_name:'',
			target:'',
			iconclass:'',
			menu_logo:'',
			menu_rights:''
		},
		rules:{
			display_order:[
				{validator:function(rule,value,callback){
								var regPos = /^-?\d+$/;
								if (value!=""&&!regPos.test(value)) {
									callback(new Error('显示顺序必须为整数'));
								}else{
									callback();
								}						
				}, trigger: 'change'}
			]
		},
		fileName:'',
		imgType: "jpg,jpeg,png",
		sizeLimit: 4,
		right:'',
		rights:[],
		privs:[],
		loadable:false,
		
//		filterText: '',
//		
//		pId: '',
//		right: {
//		  "add": false,
//		  "edit": false,
//		  "del": false
//		},

//		deptOrder: '',
//		deptRemarks: '',
//		kpJoin: '',
//		taskNum: '',
//		dutyName: '',
//		dutyPhone: '',
//		totalTask:'',

	},
	
	
	created: function(){
		tools.loadDiv();
	},
	mounted: function(){
		var that = this;
//		tools.checkPriv(data.userinfo.privNames,"dept_manage");
		this.sysName = util.getQueryString("sysName")==""?this.sysName:util.getQueryString("sysName");
		this.id = util.getQueryString("id")==""?(this.sysName=="sys_name_1"?"0":"100"):util.getQueryString("id");
		this.getTreeList();
		this.initBtns();
		this.initRights();
		this.getMenuInfo();
	},
	computed:{
		
	},
	methods: {
		toggle_bar : function() {
			if (this.show_bar) {
				this.show_bar = false;
			} else {
				this.show_bar = true;
			}
		},
		
		getTreeList : function() {
			var defaultProps = {
				children : 'children',
				label : 'label',
				id : 'id'
			};
			this.defaultProps = defaultProps;
			var reqData = {
				"id" : this.id,
				"sysName": this.sysName
			};
			data = tools.ajaxRequest("../menu/menuTree",reqData);
			this.treelist = data.tree;
			this.curTreeId = this.treelist[0].id;
			this.curTreeLevel = this.treelist[0].level;
			this.$nextTick(() => {
				 this.$refs.tree.setCurrentKey(this.treelist[0].id); 
			});
		},
		
		filterNode : function(value, data) {
			if (!value) 
				return true;
			return data.label.indexOf(value) !== -1;
		},	
		
		handleNodeClick : function(data) {			
			this.curTreeId = data.id;
			this.curTreeLevel = data.level;
			this.getMenuInfo();
			this.initBtns();
		},		
		
		getMenuInfo: function(){
			var that = this;
			var reqData ={
				"menuId" : this.curTreeId
			};
			this.menuInfo=[];
			tools.ajaxRequestAsync("../menu/menuInfo",reqData,function(data){
				if(data.respCode==0){
					that.info = data.list[0];
					console.log(data);
					that.menuInfo.push({"name":"菜单名称","value":that.info.menu_name});
					that.menuInfo.push({"name":"父菜单名称","value":that.info.menu_superior_name});
					that.menuInfo.push({"name":"是否显示","value":that.info.is_display=='Y'?'是':'否'});
					that.menuInfo.push({"name":"显示顺序","value":that.info.display_order});
					that.menuInfo.push({"name":"链接","value":that.info.menu_href});
					that.menuInfo.push({"name":"所属权限","value":that.info.menu_rights_name});
					that.menuInfo.push({"name":"目标","value":that.info.target});
					that.menuInfo.push({"name":"样式","value":that.info.iconclass});
					that.menuInfo.push({"name":"LOGO","value":that.info.menu_logo==""?that.logo:"../.."+that.info.menu_logo});
					$("#logo").bind("error",function(){
						$(this).attr("src",that.errlogo);
						$(this).unbind();
					});
					that.form = JSON.parse(JSON.stringify(that.info));	
//					that.form.menu_logo = "../.."+that.form.menu_logo;
				}else{
					that.showError(data.respDesc);
					return false;
				}
			});			
			
		},
		
		initBtns: function(){
			var reqData = {
				"menuId": this.curTreeId,
				"menuLevel": this.curTreeLevel
			};
			var data = tools.ajaxRequest("../menu/btnInfo", reqData);
			if(data.respCode=="0"){
				this.addable = Boolean(data.addRight);
				this.delable = Boolean(data.delRight);
			}else{
				this.showError("初始化数据失败");
				return false;
			}		
		},
		initRights:function(){
			var data = tools.ajaxRequest("../menu/menuRights", {});
			if(data.respCode=="0"){
				this.rights.push({"priv_group":"请选择","privs":[]});
				this.rights.push.apply(this.rights,data.rightList);
				this.privs.push({"priv_name":"-1","remarks":"请选择"});	
				
			}else{
				this.showError("初始化权限列表失败");
				return false;
			}		
		},
		
		getPrivs:function(value){
			var that = this;
			if(value!="请选择"){
				this.privs=[];
				this.privs.push({"priv_name":"-1","remarks":"请选择"});
				this.rights.forEach(function(item,idx){
					if(item.priv_group==value){
						that.privs = item.privs;
					}
				});	
			}else{
				this.privs=[];
				this.privs.push({"priv_name":"-1","remarks":"请选择"});
			}
			this.form.menu_rights = this.privs[0].priv_name;
		},		
		logoUpload: function(){
			var that = this;
			var uploader = WebUploader.create({
		        pick: {
		            id: "#upLogo",
//		            label: '点击选择文件',
		            multiple:false
		        },      
		        accept: {
		            title: 'images',
		            //extensions: 'gif,jpg,jpeg,bmp,png,mp3,mp4,mov',
		            extensions: that.imgType,
		           // mimeTypes: 'image/*,video/*,audio/*,application/pdf'
		            mimeTypes: 'image/*'
		        },		        
		        swf: '../../plugin/webuploader/Uploader.swf',
		        disableGlobalDnd: true,
		        auto:true,
		        duplicate:true,
		        server: '../menu/picPhoto',  
		        fileNumLimit: 100,
		        fileSizeLimit: that.sizeLimit * 1024 * 1024,    // 4M
		        fileSingleSizeLimit: that.sizeLimit * 1024 * 1024    // 4M
		    });
			
			uploader.refresh();
			uploader.on('uploadBeforeSend', function( block, data ) {   
					//上传文件参数
					var file = block.file;
				    data.fileName = encodeURI(file.name);	    			    
			},2);  
			
			
			uploader.on( 'uploadSuccess', function(file,response) {
				if(response.respCode=="0"){
					that.form.menu_logo = "../../"+response.fileName;
//					$("#logo").attr("src","../../"+response.fileName);
					that.fileName = response.fileName;
				}else{
					that.showError("logo上传失败");
				}			
			});		
			
			uploader.on("error",function(code, file){
				var str="";  
				if(that.imgType.indexOf(file.ext)<0){
					str="不支持上传该文件类型";
				}
				
		        switch(code){  
		         case "文件类型不支持":  
		             str= "不支持上传该文件类型";  
		             break;  
		         case "Q_EXCEED_SIZE_LIMIT":                
		            str=name+"文件大小超出限制"+that.sizeLimit+"M";   
		            break;              
		               
		         default:  
		             str="上传文件失败";  
		        }  
		        that.showError(str);	    
			});
			
		},
		
		upload:function(){
			$("#upLogo input").trigger("click");
		},
		
//		reset: function(){
//			this.pName = '';
//			this.pId = '';
//			this.deptInfo = [];	
//			this.right = {
//				  "add": false,
//				  "edit": false,
//				  "del": false
//			};
//		},
		
		
		mdfMenu: function(exec){
			var that = this;
			if(exec=="add"){
				if(this.loadable) this.$refs['form'].resetFields();
				this.menuExec = "菜单添加";
				this.form.menu_superior_name = this.form.menu_name+'';
				this.form.menu_name = '';
				this.form.is_display = 'Y';
				this.form.menu_href='';
				this.form.display_order = 0;
				this.form.menu_rights_name='';
				this.form.target = '';
				this.form.iconclass='';
				this.form.menu_logo=this.logo;
				this.right = "请选择";
				this.form.menu_rights="-1";
				this.exec = "add";
				this.menuForm = true;
				if(!this.loadable){
					this.$nextTick(() => {
						this.logoUpload();
						this.loadable = true;
					});			
				}
				
			}else if(exec=="edit"){
				this.menuExec = "菜单编辑"; 
				this.form.menu_logo = this.info.menu_logo==""?this.logo:"../../"+this.info.menu_logo;
				if(this.form.menu_rights=="-1"||this.form.menu_rights==""){
					this.right = "请选择";
					this.getPrivs(this.right);
				}else{
					this.rights.forEach(function(item,idx){
						for(var i=0;i<item.privs.length;i++){
							var priv = item.privs[i];
							if(priv.priv_name==that.form.menu_rights){
								that.right = item.priv_group;
								that.getPrivs(that.right);
								that.form.menu_rights = that.info.menu_rights;
							}
						}
					});
				}
				this.exec = "edit";
				this.menuForm = true;
				if(!this.loadable){
					this.$nextTick(() => {
						this.logoUpload();
						this.loadable =true;
					});
				}
			}else if(exec=="del"){
				this.$confirm('此操作将删除菜单 【'+this.info.menu_name+'】 , 是否继续?', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			        }).then(() => {
			          var reqData = {
			        	 "menuId" : that.curTreeId
			          };
			          tools.ajaxRequestAsync("../menu/delMenu",reqData,function(data){
			        	  console.log(data);
			        	  if(data.respCode=="0"){
			        		  that.$message({
						        	showClose: true,
						            type: 'success',
						            message: '删除成功!'
						       });
			        		  that.getTreeList();
			        		  that.curTreeId = data.menu_superior;
			        		  that.curTreeLevel = data.menu_grade;
			        		  that.getMenuInfo();
			  				  that.initBtns();
			        	  }else{
			        		  that.showError("删除失败");
			        	  }			        	  
			          });
//			          
//			          
			        }).catch(() => {        
			    
			        });
				
			}				

		},		
		
		close:function(){
			this.form = JSON.parse(JSON.stringify(this.info));
			this.$refs['form'].resetFields();
		},
//		
		save: function(){
			var that = this;
			var reqData = {};
			this.$refs['form'].validate((valid) => {
		          if (valid) {		        	
		  			if(this.form.menu_name.trim()==""){
		  				that.showError("菜单名不能为空");
		  				return false;
		  			}
		  			if(this.form.display_order==""){
		  				that.showError("显示顺序不能为空");
		  				return false;
		  			}
		  			var logo = this.form.menu_logo;
		  			if(logo!=that.logo&&logo!=that.errlogo){
		  				logo = logo.replace("../../","");
		  			}else{
		  				logo = "";
		  			}
		  			var jsonStr = {
		  				"name": this.form.menu_name,
		  				"display": this.form.is_display,
		  				"url": this.form.menu_href,
		  				"order": this.form.display_order,
		  				"priv": this.form.menu_rights=="-1"?"":this.form.menu_rights,
		  				"target": this.form.target,
//		  				"iconclass": this.form.iconclass==""?"glyphicon glyphicon-chevron-right":this.form.iconclass,
		  				"iconclass": this.form.iconclass==""?"":this.form.iconclass,
		  				"logo": logo
		  			};
		  			var reqData = {
		  				"menuId": this.curTreeId,
		  				"menuLevel": this.curTreeLevel,
		  				"operType": this.exec,
		  				"sysName": this.sysName,
		  				"jsonStr": JSON.stringify(jsonStr)
		  			};
		  			tools.ajaxRequestAsync("../menu/saveMenu", reqData, function(data){
		  				if(data.respCode=="0"){
		  					that.$message({
		  						  showClose: true,
		  				          message: '保存成功',
		  				          type: 'success'
		  				    });
		  					that.menuExec = '';
		  					that.menuForm = false;
		  					that.getTreeList();
		  					that.curTreeId = data.menuId;
		  					that.curTreeLevel = data.menuLevel;
		  					that.getMenuInfo();
		  					that.initBtns();
//		  					that.$refs['form'].resetFields();
		  				}else{
		  					that.showError(data.respDesc);
		  					return false;
		  				}
		  			});
		  			
		          } else {
		            return false;
		          }
		    });
	
		},
		
		cancel: function(){
			this.menuExec = '';
			this.menuForm = false;
			this.form = JSON.parse(JSON.stringify(this.info));
			this.$refs['form'].resetFields();
		},
		
		
		showError: function(info){
			var i = (info==undefined?"加载数据错误":info);
			this.$alert(i, '系统错误', {
		          confirmButtonText: '确定'
		    });	
		}
		
	},
	watch:{
//		curTreeId : function() {
//			// alert(this.currentPageNbr);
//			this.getMenuInfo();
//		}
	}
});

